package com.jframe.cfg.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jframe.cfg.model.Sysmenu;
import com.jframe.cfg.service.SysmenuService;
import com.jframe.sso.model.UserGroup;
import com.jframe.sso.service.UserGroupService;
import com.jframe.sys.controller.ExtendAction;
import com.jframe.sys.controller.utils.*;
import com.jframe.sys.orm.service.BaseService;
import com.jframe.sys.utils.*;
import com.jframe.sys.webui.*;



public class SysmenuAction extends ExtendAction{
	
	private static String ACTION="sysMenuAction";
	private static String SERVICE="sysmenuService";
	private static Class<Sysmenu> CLAZZ=Sysmenu.class;
	
	public void list(){
		String groupId = this.pageInfo.getPageTabId(request);
		//加载数据字典
		List<Columns> frozenColumns = new ArrayList<Columns>();//固定列
		List<Columns> commonColumns = new ArrayList<Columns>();
		frozenColumns.add(new Columns("ck","",40,""));
		frozenColumns.add(new Columns("id", "编号", 80,""));
		frozenColumns.add(new Columns("code", "权限代码", 100,""));
		frozenColumns.add(new Columns("text","名称",150,""));		
		commonColumns.add(new Columns("upId","父菜单",120,new Editor("combobox",true),TabmCache.getComboboxJson("sm_sys_menu")));
		commonColumns.add(new Columns("url","链接",250,""));
		commonColumns.add(new Columns("iconCls","图标",170,""));
		commonColumns.add(new Columns("seq","顺序",80,""));
		commonColumns.add(new Columns("active","有效否",100,new Editor("combobox",true),DicCache.getComboboxJson("dm_sys_active")));
		Grid grid = new Grid();
		grid.setSortName("seq");
		grid.setSortOrder("asc");
		grid.setUrl(ACTION+".do?method=load&groupId="+groupId);
		String js = JsBuilder.getJsStr(frozenColumns, commonColumns, grid);
		this.request.setAttribute("js", js);
		this.request.setAttribute("groupId", groupId);
		this.forward("/jframe/cfg/list/sysmenuList.jsp");
	}
	
	public void load(){
		int groupId = StringUtil.parseInt(this.request.getParameter("groupId"));
		this.baseLoad(SERVICE, CLAZZ, " and groupId=? ","order by seq,id", groupId);		
	}
	
	public void save(){
		String obj = this.request.getParameter("obj");
		String type = this.request.getParameter("type");
		Sysmenu sysmenu = (Sysmenu) JsonUtil.json2Obj(obj,Sysmenu.class);
		Map<String,Object> map = new HashMap<String,Object>();
		SysmenuService sysmenuService = (SysmenuService)this.getBean("sysmenuService");	
		//设置新增节点为叶子
		sysmenu.setLeaf(1);
		if(type.equals("edit")){
			//获取未修改前节点
			Sysmenu menu = sysmenuService.load(sysmenu.getId());
			//获取未修改前父节点
			Sysmenu upMenu = sysmenuService.load(menu.getUpId());
			//查找该父节点下的子节点
			List<Sysmenu> upls = sysmenuService.findListByUpId(menu.getUpId());
			//若子节点数小于等于1，择修改leaf为1（叶子）
			if(upls.size()<2){
				upMenu.setLeaf(1);
				sysmenuService.save(upMenu);
			}
			List<Sysmenu> downls = sysmenuService.findListByUpId(menu.getId());
			if(downls.size()>0){
				sysmenu.setLeaf(0);
			}
		}else{
			Sysmenu menu1 = sysmenuService.load("code", sysmenu.getCode());
			if(!StringUtil.null2Space(menu1.getText()).equals("")){
				map.put("result", false);
				return;
			}
		}
		//获取新父节点
		Sysmenu menu = sysmenuService.load(sysmenu.getUpId());
		//父节点原先是否为叶子 0：不修改，1：修改为0
		if(menu.getLeaf()==1){
			menu.setLeaf(0);
			sysmenuService.save(menu);
		}		
		//保存
		sysmenuService.save(sysmenu);
		TabmCache.reload("sm_sys_menu");//刷新缓存
		TabmCache.reload("sm_sys_menu_code");//刷新缓存	
		map.put("result", true);
		map.put("obj", sysmenu);
		this.print(JsonUtil.map2Json(map));
	}

	public void getObjById(){
		this.print(JsonUtil.obj2Json(this.getObject(SERVICE)));
	}
	
	public void delete(){
		String ids = this.request.getParameter("ids");
		SysmenuService sysmenuService = (SysmenuService)this.getBean("sysmenuService");
		List<Sysmenu> ls = sysmenuService.findListByIds(ids);

		sysmenuService.del(ids);
		afterDelete(ids);
		
		for(Sysmenu menu : ls){
			List<Sysmenu> upls = sysmenuService.findListByUpId(menu.getUpId());
			Sysmenu upMenu = sysmenuService.load(menu.getUpId());
			//若子节点数小于等于1，择修改leaf为1（叶子）
			if(upls.size()<1){				
				upMenu.setLeaf(1);		
			}else{
				upMenu.setLeaf(0);
			}		
			sysmenuService.save(upMenu);			
		}
		TabmCache.reload("sm_sys_menu");//刷新缓存
		TabmCache.reload("sm_sys_menu_code");//刷新缓存
		this.print("true");
	}
	
	public void getUpData(){
		int groupId = StringUtil.parseInt(this.request.getParameter("groupId"));		
		SysmenuService sysmenuService = (SysmenuService)this.getBean("sysmenuService");
		List<Sysmenu> ls = sysmenuService.findListByUpIdAndGroupId(0,groupId);
		String json = "[";
		for(Sysmenu menu:ls){
			json +="{\"id\":"+menu.getId()+",";
			json +="\"text\":\""+menu.getText()+"\"";
			if(menu.getLeaf()==0){		
				json+=",\"state\":\"closed\",";
				json+="\"children\":"+this.getChildTree(menu.getId(), groupId);
			}
			json+="},";
		}
		//去除尾部逗号
		if(ls.size()>0){
			json = json.substring(0,json.length()-1);
		}
		json += "]";
		this.print(json);
	}
	
	private String getChildTree(int upId,int groupId){
		SysmenuService sysmenuService = (SysmenuService)this.getBean("sysmenuService");
		List<Sysmenu> ls = sysmenuService. findListByUpIdAndGroupId(upId,groupId);
		String json = "[";
		for(Sysmenu menu:ls){
			json +="{\"id\":"+menu.getId()+",";
			json +="\"text\":\""+menu.getText()+"\"";
			if(menu.getLeaf()==0){
				json+=",\"state\":\"closed\",";
				json+="\"children\":"+this.getChildTree(menu.getId(), groupId);
			}
			json+="},";
		}
		//去除尾部逗号
		if(ls.size()>0){
			json = json.substring(0,json.length()-1);
		}
		json += "]";
		return json;
	}
	
	public void getGroups(){
		int groupId = StringUtil.parseInt(this.request.getParameter("groupId"));
		SysmenuService sysmenuService = (SysmenuService)SpringUtil.getBean("sysmenuService");
		int id = StringUtil.parseInt(this.request.getParameter("id"));
		List<Sysmenu> treels = sysmenuService.findListByUpIdAndGroupId(id, groupId);
		List<Tree> ls = new ArrayList<Tree>();
		for(Sysmenu menu:treels){
			Tree tree = new Tree();
			tree.setId(""+menu.getId());
			tree.setIconCls(menu.getIconCls());
			tree.setText(menu.getText());
			if(menu.getLeaf()==0){
				tree.setState("closed");	
			}
			ls.add(tree);
		}
		this.print(JsonUtil.list2Json(ls));
	}
	
	public List<UserGroup> getUserGroups(){
		UserGroupService userGroupService = (UserGroupService)this.getBean("userGroupService");
		List<UserGroup> ls = userGroupService.findList("where active=1 order by id");
		return ls;
	}
	
	public void getRightTrees(){
		int groupId = StringUtil.parseInt(this.request.getParameter("groupId"));
		SysmenuService sysmenuService = (SysmenuService)SpringUtil.getBean("sysmenuService");
		int id = StringUtil.parseInt(this.request.getParameter("id"));
		List<Sysmenu> treels = sysmenuService.findListByUpIdAndGroupId(id, groupId);
		List<Tree> ls = new ArrayList<Tree>();
		for(Sysmenu menu:treels){
			Tree tree = new Tree();
			tree.setId(""+menu.getId());
			tree.setIconCls(menu.getIconCls());
			tree.setText(menu.getText());
			if(menu.getLeaf()==0){
				tree.setState("closed");
			}
			ls.add(tree);
		}
		this.print(JsonUtil.list2Json(ls));
	}
}
